package com.ht.api.callback.impl;
import java.util.List;

import javax.sql.DataSource;

import com.ht.api.db.Db;
import com.ht.api.db.Entity;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

/**
 * 客户接替失败事件
 * @author asq
 * @createTime 2025年1月17日 13:26:47
 */
@Slf4j
public class WwxTransferFailCallbackFunction extends BaseCallbackFunction {
	@Override
	protected List<String> buildSourceDataList(JSONObject params) {
		DataSource ds = getTenantDs(appid);
		String userid = params.getStr("UserID");
		String externalUserid = params.getStr("ExternalUserID");
		String failReason = params.getStr("FailReason");

		// 更新客服接替明细表状态
		DateTime date1DaysAgo = DateUtil.offsetDay(DateUtil.date(), -1);
		String date1 = DateUtil.formatDateTime(date1DaysAgo);
		Entity wxTransferUserItem = Db.createSqlParser("wx_transfer_user_item")
				.where("appid", appid)
				.where("takeover_userid", userid)
				.where("external_userid", externalUserid)
				.where("status", 1)
				.where("execute_time", ">=", date1)
				.findOne(ds);
		if (wxTransferUserItem != null) {
			String handoverUserid = wxTransferUserItem.getStr("handover_userid");
			
			if ("customer_refused".equals(failReason)) {
				wxTransferUserItem.set("status", 3); // 客户拒绝
				Db.insert(ds, wxTransferUserItem);
			} else if ("customer_limit_exceed".equals(failReason)) {
				wxTransferUserItem.set("status", 4); // 接替成员客户达到上限
				Db.insert(ds, wxTransferUserItem);
			}
			
			// 更新客服接替表失败数+1
			Entity wxTransferUser = Entity.create("wx_transfer_user");
			wxTransferUser.setMainId(wxTransferUserItem.getStr("transfer_id"));
			wxTransferUser.set("fail_cnt", 1);
			Db.insert(ds, wxTransferUser);
			
			// 如果是离职继承
			int type = Db.createSqlParser("wx_transfer_user").select("type")
					.where("main_id", wxTransferUserItem.getStr("transfer_id")).val(ds, Integer.class);
			if (type == 1) {
				// 更新离职成员表的待继承数量
				Entity wxWorkuserDimission = Entity.create("wx_workuser_dimission");
				wxWorkuserDimission.set("appid", appid);
				wxWorkuserDimission.set("handover_userid", handoverUserid);
				wxWorkuserDimission.set("wait_cnt", 1);
				Db.insert(ds, wxWorkuserDimission);
				
				// 更新离职成员待分配的外部用户表状态
				Entity wxWorkuserDimissionExternal = Db.createEntity("wx_workuser_dimission_external");
				wxWorkuserDimissionExternal.set("appid", appid); 
				wxWorkuserDimissionExternal.set("handover_userid", handoverUserid);
				wxWorkuserDimissionExternal.set("external_userid", externalUserid);
				wxWorkuserDimissionExternal.set("status", 5); // 等待再分配
				Db.insert(ds, wxWorkuserDimissionExternal);
			}
		}

		return null;
	}
}
